<template>
	<div class="table-head">
		<el-form ref="searchRef" :model="query" :inline="true">
			<el-row>
				<el-form-item>
					<el-input v-model="query.studentName" placeholder="请输入考生姓名" clearable></el-input>
					<el-input v-model="query.studentId" placeholder="请输入考生身份证号" clearable></el-input>
				</el-form-item>
			</el-row>
			<el-row>
				<el-form-item>
					<el-select v-model="query.licenceType" clearable placeholder="请选择驾驶证类型" style="width: 240px">
						<el-option v-for="item in licenseOptions" :key="item.value" :label="item.label"
							:value="item.value" />
					</el-select>
					<el-input v-model="query.subject" placeholder="请输入考试科目" clearable></el-input>
				</el-form-item>
				<el-form-item>
					<el-date-picker v-model="query.examDate" placeholder="请选择考试日期"></el-date-picker>
				</el-form-item>
			</el-row>

			<el-form-item>
				<el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
				<el-button :icon="Refresh" @click="resetForm(searchRef)">重置</el-button>
			</el-form-item>
		</el-form>
	</div>
	<div class="table-body">
		<el-table :data="tableData" :default-sort="[{ prop: 'examDate', order: 'descending' },
		{ prop: 'registDate', order: 'descending' }]" style="width: 100%">
			<el-table-column fixed prop="appTime" :formatter="formatAppTime" sortable label="报名日期" width="150" />
			<el-table-column fixed prop="examTime" :formatter="formatAppTime" sortable label="考试日期" width="150" />
			<el-table-column prop="student.studentName" label="姓名" />
			<el-table-column prop="licence.licenceType" label="驾驶证类型" />
			<el-table-column prop="subject.subjectType" label="考试科目" />
			<el-table-column prop="examScore" label="考试成绩">
				<template #slot-scope>
					<el-tag>{{ scope.row.examScore }}</el-tag>
				</template>
			</el-table-column>
			<el-table-column fixed="right" label="操作" width="150" :filters="[
			{ text: '已出成绩', value: 'already' },
			{ text: '未出成绩', value: 'not' },
			{ text: '合格', value: 'passed' },
			{ text: '不合格', value: 'not_passed' }]" :filter-method="filterHandler" filter-placement="bottom-end">
				<template #default="scope">
					<div v-if="role == 'student'" class="button-group">
						<el-button type="success" round @click="handlePrintExam(scope.row)">
							打印成绩单
						</el-button>
						<el-button type="primary" round @click="handleDownExam(scope.row)">
							下载成绩单
						</el-button>

					</div>
					<div v-else-if="role == 'coach'" class="button-group">
						<el-tooltip v-if="scope.row.examScore !== ''" content="已出结果的成绩不能再打分" placement="top">
							<el-button type="success" round :disabled="scope.row.examScore !== ''"
								@click="handleMark(scope.row)">
								打分
							</el-button>
						</el-tooltip>
						<el-button v-else type="success" round :disabled="scope.row.examScore !== ''"
							@click="handleMark(scope.row)">
							打分
						</el-button>
						<el-button type="primary" round @click="handleView(scope.row)">详情</el-button>
					</div>
					<div v-else-if="role == 'admin'" class="button-group">
						<el-button type="warning" round size="small" @click="handleEdit(scope.row)">
							编辑
						</el-button>
						<el-button type="info" round size="small" @click="handleView(scope.row)">详情</el-button>
					</div>
				</template>
			</el-table-column>
		</el-table>
		<el-dialog :title="isEdit ? (isMark ? '考试打分' : '编辑') : '新增'" v-model="visible" width="700px" destroy-on-close
			:close-on-click-modal="false" @close="closeDialog">
			<TableEdit :formData="rowData" :options="isMark ? optionsForCoach : options" :edit="isEdit"
				:update="updateData">
			</TableEdit>
		</el-dialog>
		<el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
			<TableDetail :data="viewData">
			</TableDetail>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive } from 'vue';
import { ElMessage, FormInstance, ElIcon, ElForm } from 'element-plus';
import { fetchData } from '@/api/index';
import { TableItem } from '@/types/table';
import { FormOption, FormOptionList } from '@/types/form-option';
import { jsPDF } from 'jspdf';

import * as studentApi from '@/api/student';
import * as licenceApi from '@/api/licence';
import * as processApi from '@/api/process';
import * as examApi from '@/api/exam';
import { examItemData } from '@/api/exam';

// 查询相关
const query = reactive({
	studentName: '',
	studentId: '',
	licenceType: '',
	subject: '',
	examDate: null,
});

//驾驶证类型
const licenseOptions = ref<Array<{ value: string; label: string }>>([
	{ value: '', label: '加载中...' }
]);
const initLicenceOption = async () => {
	try {
		const resp = await licenceApi.fetchData();
		licenseOptions.value = resp.data.licences.map((element: any) => ({
			value: element.licenceId,
			label: element.licenceType
		}));
	} catch (error) {
		console.error(error);
	}
};

//查询、筛选相关
const resetForm = () => {
	query.studentName = '';
	query.studentId = '';
	query.licenceType = '';
	query.subject = '';
	query.examDate = null;
};
const handleSearch = () => {
	console.log(query);
};
const filterHandler = (value, row) => {
	if (value === 'passed') {
		return row['examScore'] >= 90;
	} else if (value === 'not_passed') {
		return row['examScore'] < 90; // 同上
	} else if (value === 'already') {
		return row['examScore'] != '';
	} else if (value === 'not') {
		return row['examScore'] == '';
	}
}

const role = localStorage.getItem('vuems_name');
const storedStudentInfo = localStorage.getItem("studentInfo");
const studentId = ref(JSON.parse(storedStudentInfo).studentId);
console.log(role);
const page = reactive({
	index: 1,
	size: 10,
	total: 200,
})
const tableData = ref<examItemData[]>([]);
const formatAppTime = (row, column, cellValue, index) => {
	// 自定义处理数据的逻辑
	// 例如，将日期格式化为 yyyy-MM-dd
	const date = new Date(cellValue);
	const year = date.getFullYear();
	const month = (date.getMonth() + 1).toString().padStart(2, '0');
	const day = date.getDate().toString().padStart(2, '0');
	return `${year}-${month}-${day}`;
}
//不同权限获取数据
const getData = async () => {
	//学员
	if (role == "student") {
		const response = await examApi.findByStudentID(studentId.value);
		tableData.value = response.data.data.getExam;
	} else if (role == "coach") {
		const storedCoachInfo = localStorage.getItem("coachInfo");
		const coachId = ref(JSON.parse(storedCoachInfo).coachId);
		const response = await examApi.findByCoachID(coachId.value);
		tableData.value = response.data.data.findByCoachID;
	} else if (role == "admin") {
		const response = await examApi.findAllExam();
		tableData.value = response.data.data.findAllExam;
	}
	console.log(tableData.value);
};
getData();
initLicenceOption();

//操作相关
//打印成绩单
const handlePrintExam = (rowData) => {
	const printContent = `
        <div>
          <h2>成绩单</h2>
          <p>姓名: ${rowData.student.studentName}</p>
          <p>驾驶证类型: ${rowData.licence.licenceType}</p>
          <p>考试科目: ${rowData.subject.subjectType}</p>
          <p>考试成绩: ${rowData.examScore}</p>
          <p>报名日期: ${rowData.appTime}</p>
          <p>考试日期: ${rowData.examTime}</p>
        </div>
      `;
	const newWindow = window.open('', '_blank');
	newWindow.document.write(printContent);
	newWindow.document.close();
	newWindow.print();
}
//以PDF形式下载成绩单
const handleDownExam = (row) => {
	const doc = new jsPDF();
	doc.text(`成绩单`, 20, 20);
	doc.text(`姓名: ${row.student.studentName}`, 20, 30);
	doc.text(`驾驶证类型: ${row.licence.licenceType}`, 20, 40);
	doc.text(`考试科目: ${row.subject.subjectType}`, 20, 50);
	doc.text(`考试成绩: ${row.examScore}`, 20, 60);
	doc.text(`报名日期: ${row.appTime}`, 20, 70);
	doc.text(`考试日期: ${row.examTime}`, 20, 80);
	doc.save(`${row.student.studentName}_成绩单.pdf`);
}
// 新增/编辑弹窗相关
let options = ref<FormOption>({
	labelWidth: '100px',
	span: 24,
	list: [
		{ type: 'input', label: '考生姓名', prop: 'studentName', required: true },
		{ type: 'date', label: '报名时间', prop: 'appDate', required: true },
		{ type: 'date', label: '考试时间', prop: 'examDate', required: true },
		{ type: 'number', label: '考试成绩', prop: 'examScore', required: true },
	]
})
let optionsForCoach = ref<FormOption>({
	labelWidth: '100px',
	span: 24,
	list: [
		{ type: 'input', label: '考生姓名', prop: 'studentName', required: true, disabled: true },
		{ type: 'date', label: '报名时间', prop: 'appDate', required: true, disabled: true },
		{ type: 'date', label: '考试时间', prop: 'examDate', required: true, disabled: true },
		{ type: 'number', label: '考试成绩', prop: 'examScore', required: true },
	]
})
const visible = ref(false);
const markVisible = ref(false);
const isEdit = ref(false);
const isMark = ref(false)
const rowData = ref({});
const handleEdit = (row) => {
	row.studentName = row.student.studentName;
	row.licenceType = row.licence.licenceType;
	row.subjectType = row.subject.subjectType;
	row.appDate = formatAppTime(1, 1, new Date(row.appTime), 1);
	row.examDate = formatAppTime(1, 1, new Date(row.examTime), 1);
	rowData.value = { ...row };
	isEdit.value = true;
	visible.value = true;
};
const handleMark = (row) => {
	isMark.value = true;
	handleEdit(row);
};
const updateData = async (data) => {
	// data.student.studentName = data.studentName;
	// data.licence.licenceType = data.licenceType;
	// data.subject.subjectType = data.subjectType;
	// data.appTime = new Date(data.appDate);
	// data.examTime = new Date(data.examDate);
	// delete data.studentName;
	// delete data.licenceType;
	// delete data.subjectType;
	// delete data.appDate;
	// delete data.examDate;
	await examApi.updateExam(data.examScore,data.examId).then((resp) => {
		console.log(resp);
		if (resp.data.message == "更新考试成绩失败") {
			ElMessage.error("更新失败");
		} else {
			ElMessage.success("更新数据成功");
			closeDialog();
			getData();
		}
	}).catch((error) => {
		console.log(error);
		ElMessage.error("更新失败");
	})
	// await examApi.updateExam(data as examItemData).then((resp) => {
	// 	console.log(resp);
	// 	if (resp.data.message == "更新考试成绩失败") {
	// 		ElMessage.error("更新失败");
	// 	} else {
	// 		ElMessage.success("更新数据成功");
	// 		closeDialog();
	// 		getData();
	// 	}
	// }).catch((error) => {
	// 	console.log(error);
	// 	ElMessage.error("更新失败");
	// })
};

const closeDialog = () => {
	visible.value = false;
	isEdit.value = false;
};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
	row: {},
	list: []
});
const handleView = (row) => {
	row.studentName = row.student.studentName;
	row.studentIdentityId = row.student.studentIdentityId;
	row.licenceType = row.licence.licenceType + '驾驶证';
	row.subjectType = row.subject.subjectType;
	row.appDate = formatAppTime(1, 1, new Date(row.appTime), 1);
	row.examDate = formatAppTime(1, 1, new Date(row.examTime), 1);
	viewData.value.row = { ...row };
	viewData.value.list = [
		{
			prop: 'studentId',
			label: '学员ID',
		},
		{
			prop: 'studentName',
			label: '考生姓名',
		},
		{
			prop: 'studentIdentityId',
			label: '身份证号',
		},
		{
			prop: 'appDate',
			label: '报名时间',
		},
		{
			prop: 'examDate',
			label: '考试时间',
		},
		{
			prop: 'licenceType',
			label: '驾驶证类型',
		},
		{
			prop: 'subjectType',
			label: '考试科目',
		},
		{
			prop: 'examId',
			label: '准考证号',
		},
		{
			prop: 'examScore',
			label: '考试成绩',
		},
	]
	visible1.value = true;
};

// 删除相关
const handleDelete = (row: TableItem) => {
	ElMessage.success('删除成功');
}
</script>

<style scoped>
.table-td-thumb {
	display: block;
	margin: auto;
	width: 40px;
	height: 40px;
}

.table-head {
	padding: 20px 30px 0;
	background-color: #fff;
	margin-bottom: 10px;
	border: 1px solid #ddd;
	border-radius: 5px
}

.el-form-item {
	margin-right: 20px;
}

.el-button {
	margin-right: 10px;
}

.el-input,
.el-select,
.el-date-picker {
	width: 200px;
	margin-right: 10px;
}

.button-group {
	display: flex;
	gap: 10px;
	flex-wrap: wrap;
}

.el-button {
	margin: 5px 0;
}
</style>
